import React,{useEffect} from 'react'
import {useSelector,useDispatch} from "react-redux"
import { ProductCard, Tag, Button } from 'react-vant';
import { Minus , Plus } from '@react-vant/icons';
import * as action from "../../action"
import { Checkbox } from 'react-vant'
import { SubmitBar } from 'react-vant';
import { useState } from 'react';
function Shopcar() {
  let [mysum,setmySum] = useState(0)
  let [mycount,setMycount] = useState(0)
  let dispacth = useDispatch()
  let store = useSelector((state)=>{
    return {
      ...state.shopreducer
    }
  })
  let addfn = (id)=> { // 调用action里的方法
      dispacth(action.addFn(id))
  }
  let removeFn = (id)=> {
      dispacth(action.RemoveFn(id))
  }
  let changefn = (id)=>{
     dispacth(action.changeFn(id))
  }
  let checkall = ()=>{
    dispacth(action.checkallfn())
  }
  useEffect(()=>{
     let newshoparr =  store.shoparr.filter(item=>item.flag)
    let sum = newshoparr.reduce((a,b)=>{
       return a + b.price * b.num
     },0)
    let count = newshoparr.reduce((a,b)=>{
      return a +  b.num
    },0)
    setMycount(count)
     setmySum(sum)
  },[store.shoparr])
  return (
    <div>
      <h4>全选:<input type="checkbox" checked={store.cheackall} onChange={checkall}/></h4>
      {
        store.shoparr &&  store.shoparr.length ?  store.shoparr.map((item,index)=>{
            return <ProductCard
            num={item.num}
            key={index}
            price={item.price}
            desc={item.des}
            title={item.tit}
            thumb={item.img}
            footer={
              <>
                <input type="checkbox" checked={item.flag} onChange = {()=>changefn(item.id)}  />
                <Button size="mini" round plain style={{ marginRight: 2 }} onClick={()=>removeFn(item.id)}>
                    <Minus  />
                </Button>
                <Button size="mini" round plain onClick={()=>addfn(item.id)}>
                    <Plus  />
                </Button>
              </>
            }
          />
        }):""
      }
      <SubmitBar price={mysum*100} buttonText="提交订单"  tip={
        <>
          您选中的商品个数为
          <span style={{ color: '#1989fa' }}>{}</span>{mycount}<span>个</span>
        </>
      }
    ></SubmitBar>
    </div>
  )
}

export default Shopcar